﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ProjectCommon
{
    public class ProcessHelper
    {
        public static bool Run(string processName)
        {
            Process.Start(processName);
            return IsRunning(processName);
        }

        public static bool IsRunning(string processName)
        {
            if (string.IsNullOrEmpty(processName))
                throw new ArgumentNullException("processName");

            return (GetProcess(processName) != null);
        }

        public static Process GetProcess(string processName)
        {
            if (string.IsNullOrEmpty(processName))
                throw new ArgumentNullException("processName");

            Process[] _Array;
            _Array = Process.GetProcessesByName(processName);

            if (_Array.Length == 0)
                return null;

            return _Array[0];
        }

        public static bool KillProcess(string processName)
        {
            if (string.IsNullOrEmpty(processName))
                throw new ArgumentNullException("processName");

            // fet process

            Process _Process;
            _Process = GetProcess(processName);

            // cannot kill

            if (_Process == null)
                throw new Exception("Process " + processName + " is not running.");

            // kill

            return KillProcess(_Process);
        }

        public static bool KillProcess(Process process)
        {
            if (process == null)
                throw new ArgumentNullException("process");

            // persist id for test

            int _ProessId;
            _ProessId = process.Id;

            // kill

            process.Kill();

            // success?

            try
            {
                Process.GetProcessById(_ProessId);
                return false;
            }
            catch
            {
                return true;
            }
        }
    }
}
